function gaze_data = generate_gazes(dump_name)
% Takes the raw eye tracking data and generates a table of "gazes", 
% where one gaze is defined as a uninterrupted period looking at one
% stimulus-location. Here stimuli are the left number (-1), right number (1),
% region in between (0) and anywhere else (9). 
%% preparing data

raw_data = readtable(dump_name);

gaze_data=raw_data;

% remove -1 values
gaze_data(gaze_data.GazeX<=0 | gaze_data.GazeY<=0 | isnan(gaze_data.GazeX) | isnan(gaze_data.GazeY),:) = [];

%% categorize x and y

locations = [];
for n = 1:height(gaze_data)
    x = gaze_data.GazeX(n);
    y = gaze_data.GazeY(n);
    if y >= 344 && y <= 680
        % if fix is in the left square
        if x >= 213 && x <= 556
            locations = [locations; -1];
        % if fix is in the center
        elseif x > 556 && x < 724
            locations = [locations; 0];
        % if fix is in the right square
        elseif x >= 724 && x <= 1067
            locations = [locations; 1];
        else
            locations = [locations; 9];
        end
    else
        locations = [locations; 9];
    end
end
gaze_data.Location = locations;
%% find change indices, take only rows where a change occurred
prevLocation = gaze_data.Location(1);
prevStim = gaze_data.StimulusName(1);
changes = [];
changes(1) = 1;
for n = 1:height(gaze_data)
    if gaze_data.Location(n) ~= prevLocation || gaze_data.StimulusName(n) ~= prevStim
        changes = [changes;n];
        prevLocation = gaze_data.Location(n);
        prevStim = gaze_data.StimulusName(n);
    end
end

gaze_data = gaze_data(changes,:);
%% get gaze lengths, remove gaze lengths only after a threshold
times = [];
for n = 1:height(gaze_data) - 1
    times(n) = gaze_data.TimeSignal(n + 1) - gaze_data.TimeSignal(n);
end

times(n + 1) = raw_data.TimeSignal(length(raw_data.TimeSignal)) - gaze_data.TimeSignal(n + 1);

gaze_data.GazeTime = times.';

% remove gaze lengths below a threshold
threshold = 30;
toRemove = [];
for n = 1:length(gaze_data.GazeTime)
    if gaze_data.GazeTime(n) < threshold
        toRemove = [toRemove, n];
    end
end

gaze_data(toRemove,:) = [];

% collapse consecutive gazes
gazeTimes = [];
toRemove = [];

prevStim = gaze_data.StimulusName(1);
prevLocation = gaze_data.Location(1);
fix = gaze_data.GazeTime(1);

for n = 2:height(gaze_data)
    if (gaze_data.Location(n) == prevLocation) && (gaze_data.StimulusName(n) == prevStim)
        toRemove = [toRemove;n];
        fix = fix + gaze_data.GazeTime(n);
    else
        gazeTimes = [gazeTimes; fix];
        prevLocation = gaze_data.Location(n);
        prevStim = gaze_data.StimulusName(n);
        fix = gaze_data.GazeTime(n);
    end
end

% collapse the last gaze
gazeTimes = [gazeTimes;fix];

gaze_data(toRemove,:) = [];
gaze_data.GazeTime = gazeTimes;
end